package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.mapper.StudentSignInMapper;
import com.xmy.cultivate.service.IBrushSignSchoolService;
import com.xmy.cultivate.service.IOrderDetailService;
import com.xmy.cultivate.service.IStudentSignInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.IStudentSignInTempService;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 刷脸签到 服务实现类
 * </p>
 *
 * @author min
 * @since 2023-01-04
 */
@Service
public class StudentSignInServiceImpl extends ServiceImpl<StudentSignInMapper, StudentSignIn> implements IStudentSignInService {

    @Autowired
    StudentSignInMapper studentSignInMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IStudentSignInTempService iStudentSignInTempService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IBrushSignSchoolService iBrushSignSchoolService;

    @Autowired
    IdWorker idWorker;

    @Override
    public StudentSignIn getSiginOneForSchedulingDetailId(Long studentId,Long schedulingDetailId){
       return studentSignInMapper.getSiginOneForSchedulingDetailId(studentId,schedulingDetailId);
    }

    @Override
    public boolean fnSaveOrUpdate(FaceGetScheduling faceGetScheduling, Student student, String ossImageUrl, LocalDateTime dateTimeNow){

        LocalDate localDate = LocalDate.now();

        Integer signType = faceGetScheduling.getType();


        StudentSignIn studentSignIn = new StudentSignIn();
        studentSignIn.setYearPart(faceGetScheduling.getYearPart());
        studentSignIn.setQuarterNum(faceGetScheduling.getQuarterNum());
        studentSignIn.setLessonType(faceGetScheduling.getLessonType());
        studentSignIn.setId(faceGetScheduling.getSignInId());
        studentSignIn.setSchoolId(faceGetScheduling.getSchoolId());
        studentSignIn.setStudentId(student.getId());
        studentSignIn.setStudentName(student.getName());
        studentSignIn.setSubjectsId(faceGetScheduling.getSubjectsId());
        studentSignIn.setSchedulingDetailId(faceGetScheduling.getSchedulingDetailId());
        studentSignIn.setCourseType(faceGetScheduling.getCourseType());
        if (signType.equals(1)) {
            studentSignIn.setOssImage(ossImageUrl);
            studentSignIn.setInDateTime(dateTimeNow);
        } else if (signType.equals(2)){
            studentSignIn.setOutOssImage(ossImageUrl);
            studentSignIn.setOutDateTime(dateTimeNow);
        }
        if (faceGetScheduling.getLessonType().equals(3)){
            if (signType.equals(8)){
                studentSignIn.setBrushOssImage(ossImageUrl);
                studentSignIn.setBrushDateTime(dateTimeNow);
            }
        }

        studentSignIn.setAddDate(localDate);
        studentSignIn.setCreatedAt(dateTimeNow);
        studentSignIn.setType(signType);
        //studentSignIn.setType();
        this.saveOrUpdate(studentSignIn);
        //添加到临时表，为了记上课查询用
        iStudentSignInTempService.saveOrUpdateDataCustom(studentSignIn);
        return true;
    }


    /**
     * 获取临时上课数据
     * @param studentId
     * @param subjectsId
     * @param lessonType
     * @return
     */
    @Override
    public FaceGetScheduling getTemporaryData(Long studentId, String subjectsId, Integer lessonType, Quarter quarter){
        StudentGrade studentGrade = studentGradeMapper.getLastOne(quarter.getYearPart(),quarter.getNum(),Long.parseLong(subjectsId),studentId,lessonType);
        if (studentGrade == null){
            return null;
        }
        FaceGetScheduling faceGetScheduling = new FaceGetScheduling();

        Integer courseType = 7;
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        Long schedulingDetailId = idWorker.nextId();//临时上课，没有排课id,随机一个

        QueryWrapper<StudentSignInTemp> studentSignInTempQueryWrapper = new QueryWrapper<>();
        studentSignInTempQueryWrapper.eq("add_date", LocalDate.now());
        studentSignInTempQueryWrapper.eq("course_type", courseType);
        studentSignInTempQueryWrapper.eq("subjects_id", subjectsId);
        studentSignInTempQueryWrapper.eq("student_id", studentId);
        studentSignInTempQueryWrapper.orderByDesc("id");
        studentSignInTempQueryWrapper.last("limit 1");
        StudentSignInTemp studentSignInTemp = iStudentSignInTempService.getOne(studentSignInTempQueryWrapper);
        //type类型:1签到，2签退，3已签到，4已签退，5还未到签到时间，6还未到签退时间,7超过签退时间
        long dffMinutes;
        if (studentSignInTemp == null){
            faceGetScheduling.setType(1);
            faceGetScheduling.setIsToNext(false);
            faceGetScheduling.setSchedulingDetailId(schedulingDetailId);
        }else if (studentSignInTemp.getInDateTime()!= null){//&& studentSignInTemp.getOutDateTime()== null
            Duration duration = Duration.between(studentSignInTemp.getInDateTime(),nowDateTime);
            dffMinutes = duration.toMinutes();//上课相差分钟
            if (subjectsId.equals("1")){
                if (dffMinutes<=40){
                    faceGetScheduling.setType(3);//已签到
                    faceGetScheduling.setIsToNext(false);
                }else {
                    //已签到不要重复签到
                    //faceGetScheduling.setType(2);
                    //faceGetScheduling.setIsToNext(false);
                    //大于40分钟以上,再刷脸，可以签到第二次
                    faceGetScheduling.setType(1);
                    faceGetScheduling.setIsToNext(false);
                }
            }else{
                List<Long> signSchoolIdList = iBrushSignSchoolService.getSchoolIdList();
                //是否需要刷题交卷功能的校区
                if (signSchoolIdList.contains(studentGrade.getSchoolId())){
                    if (dffMinutes<20){
                        if (dffMinutes<5){
                            faceGetScheduling.setType(3);//已签到
                            faceGetScheduling.setIsToNext(false);//设置是否可以查找下一条
                        }else {
                            faceGetScheduling.setType(9);//还未到交卷时间
                            faceGetScheduling.setIsToNext(false);//
                        }
                    }else {
                        if (studentSignInTemp.getBrushDateTime()==null){
                            faceGetScheduling.setType(8);//交卷
                            faceGetScheduling.setIsToNext(false);
                        }else {
                            Duration durationBrush = Duration.between(studentSignInTemp.getBrushDateTime(),nowDateTime);
                            long minutsBrush = durationBrush.toMinutes();//离交卷相差多少分钟
                            if (minutsBrush<5){
                                faceGetScheduling.setType(10);//已交卷
                                faceGetScheduling.setIsToNext(false);
                            }else {
                                //已签退
                                if(studentSignInTemp.getOutDateTime()!=null){
                                    faceGetScheduling.setType(4);//已签退
                                    faceGetScheduling.setIsToNext(true);//设置是否可以查找下一条
                                }else {
                                    faceGetScheduling.setType(2);//签退
                                    faceGetScheduling.setIsToNext(false);
                                }
                            }

                        }
                    }
                }else {
                    if (dffMinutes<20){
                        faceGetScheduling.setType(3);//已签到
                        faceGetScheduling.setIsToNext(false);//设置是否可以查找下一条
                    }else {
                        //已签退
                        if(studentSignInTemp.getOutDateTime()!=null){
                            faceGetScheduling.setType(4);//已签退
                            faceGetScheduling.setIsToNext(true);//设置是否可以查找下一条
                        }else {
                            faceGetScheduling.setType(2);//签退
                            faceGetScheduling.setIsToNext(false);
                        }
                    }
                }
            }

            faceGetScheduling.setSchedulingDetailId(studentSignInTemp.getSchedulingDetailId());
            faceGetScheduling.setSignInId(studentSignInTemp.getId());
        }else if (studentSignInTemp.getOutDateTime()!= null){
            Duration duration = Duration.between(studentSignInTemp.getOutDateTime(),nowDateTime);
            dffMinutes = duration.toMinutes();//上课相差分钟
            if (dffMinutes>60){
                //大于1个小时以上,再刷脸，可以签到第二次
                faceGetScheduling.setType(1);
                faceGetScheduling.setIsToNext(false);
            }else {
                faceGetScheduling.setType(4);
                faceGetScheduling.setIsToNext(false);
            }
            faceGetScheduling.setSchedulingDetailId(studentSignInTemp.getSchedulingDetailId());
            faceGetScheduling.setSignInId(studentSignInTemp.getId());
        }

        //faceGetScheduling.setSchedulingDetailId();
        String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId));
        faceGetScheduling.setSubjectsId(Long.parseLong(subjectsId));
        faceGetScheduling.setSubjectsName(subjectsName);
        faceGetScheduling.setStatus(1);
        faceGetScheduling.setCourseType(courseType);
        faceGetScheduling.setSchoolId(studentGrade.getSchoolId());
        faceGetScheduling.setStudentId(studentId);
        String gradeName = "临时"+subjectsName+"刷题班";
        if (subjectsId.equals("1")){
            gradeName = "临时"+subjectsName+"智能课";
        }
        faceGetScheduling.setGradeName(gradeName);
        faceGetScheduling.setLessonType(lessonType);
        faceGetScheduling.setReachType(ReachTypeEnum.NORMAL);
        faceGetScheduling.setYearPart(quarter.getYearPart());
        faceGetScheduling.setQuarterNum(quarter.getNum());
        faceGetScheduling.setGradeId(studentGrade.getGradeId());
        faceGetScheduling.setYearClassId(studentGrade.getYearClassId());
        return faceGetScheduling;
    }

    /**
     * 获取试听数据
     * @param student
     * @param subjectsId
     * @param lessonType
     * @param quarter
     * @return
     */
    @Override
    public FaceGetScheduling getTryListenData(Student student, String subjectsId, Integer lessonType, Quarter quarter){
        if (student.getStuType() == null){
            return null;
        }

        if (!student.getStuType().equals(2)){
            return null;
        }

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_part", quarter.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());
        orderDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderDetailQueryWrapper.eq("student_id", student.getId());
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.ne("status", 2);
        //是否当前学期报名过
        Long count = iOrderDetailService.count(orderDetailQueryWrapper);
        if (count>0){
            return null;
        }

        FaceGetScheduling faceGetScheduling = new FaceGetScheduling();
        Integer courseType = 8;//试听
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
        Long schedulingDetailId = idWorker.nextId();//临时上课，没有排课id,随机一个
        QueryWrapper<StudentSignInTemp> studentSignInTempQueryWrapper = new QueryWrapper<>();
        studentSignInTempQueryWrapper.eq("add_date", LocalDate.now());
        studentSignInTempQueryWrapper.eq("course_type", courseType);
        studentSignInTempQueryWrapper.eq("subjects_id", subjectsId);
        studentSignInTempQueryWrapper.eq("student_id", student.getId());
        studentSignInTempQueryWrapper.orderByDesc("id");
        studentSignInTempQueryWrapper.last("limit 1");
        StudentSignInTemp studentSignInTemp = iStudentSignInTempService.getOne(studentSignInTempQueryWrapper);
        //type类型:1签到，2签退，3已签到，4已签退，5还未到签到时间，6还未到签退时间,7超过签退时间
        long dffMinutes;
        if (studentSignInTemp == null){
            faceGetScheduling.setType(1);
            faceGetScheduling.setIsToNext(false);
            faceGetScheduling.setSchedulingDetailId(schedulingDetailId);
        }else if (studentSignInTemp.getInDateTime()!= null && studentSignInTemp.getOutDateTime()== null){
            Duration duration = Duration.between(studentSignInTemp.getInDateTime(),nowDateTime);
            dffMinutes = duration.toMinutes();//上课相差分钟
            if (dffMinutes<=30){
                faceGetScheduling.setType(3);
                faceGetScheduling.setIsToNext(false);
            }else {
                faceGetScheduling.setType(2);
                faceGetScheduling.setIsToNext(false);
            }
            faceGetScheduling.setSchedulingDetailId(studentSignInTemp.getSchedulingDetailId());
            faceGetScheduling.setSignInId(studentSignInTemp.getId());
        }else if (studentSignInTemp.getOutDateTime()!= null){
            Duration duration = Duration.between(studentSignInTemp.getOutDateTime(),nowDateTime);
            dffMinutes = duration.toMinutes();//上课相差分钟
            if (dffMinutes>600){
                //大于6个小时以上,再刷脸，可以签到第二次
                faceGetScheduling.setType(1);
                faceGetScheduling.setIsToNext(false);
            }else {
                faceGetScheduling.setType(4);
                faceGetScheduling.setIsToNext(false);
            }
            faceGetScheduling.setSchedulingDetailId(studentSignInTemp.getSchedulingDetailId());
            faceGetScheduling.setSignInId(studentSignInTemp.getId());
        }

        //faceGetScheduling.setSchedulingDetailId();
        String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId));
        faceGetScheduling.setSubjectsId(Long.parseLong(subjectsId));
        faceGetScheduling.setSubjectsName(subjectsName);
        faceGetScheduling.setStatus(1);
        faceGetScheduling.setCourseType(courseType);
        faceGetScheduling.setSchoolId(student.getSchoolId());
        faceGetScheduling.setStudentId(student.getId());
        faceGetScheduling.setGradeName("试听"+subjectsName+"");
        faceGetScheduling.setLessonType(lessonType);
        faceGetScheduling.setReachType(ReachTypeEnum.NORMAL);
        faceGetScheduling.setYearPart(quarter.getYearPart());
        faceGetScheduling.setQuarterNum(quarter.getNum());
        //faceGetScheduling.setGradeId();
        faceGetScheduling.setYearClassId(student.getYearClassId());
        return faceGetScheduling;
    }
}
